<template>
 <!-- 服务清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                    <div>
                        <el-button size="small" type="primary" v-if="!isBidding" class="btn-greenYellow" @click="selectBasics">选择设备基础库</el-button>
                        <el-button size="small" type="danger" class="btn-delete"  @click="deleteData">批量删除</el-button>
                    </div>
                </div>
                <div class="right">
                    <div class="squarecolor">
                        <div class="color colorAdd"></div>
                        <span>新增</span>
                    </div>
                    <div class="squarecolor item">
                        <div class="color colorUpdate"></div>
                        <span>修改</span>
                    </div>
                    <div class="squarecolor">
                        <div class="color colorDel"></div>
                        <span>删除/过期</span>
                    </div>
                </div>
            </div>
            <div>
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                 <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    @selection-change="changeSelect"
                    :row-class-name="tableRowClassName"
                    class="table"
                    :max-height="$store.state.tableHeight"
                >
                    <el-table-column type="selection" width="50">
                    </el-table-column>
                     <el-table-column
                        label="操作"
                        fixed
                        width="100px"
                        >
                        <template slot-scope="{ row }">
                            <div class="list_box">
                                <img src="@/assets/btn/delete.png" class="cancel_delete"
                                    v-if="isAdd && row.changeState !== -1"
                                    @click="deleteEle(row)"
                                    title="删除"
                                />
                                <img src="@/assets/btn/cancelDelete.png" class="cancel_delete"
                                    @click="cancelDelete(row)"
                                        v-if="isAdd && row.changeState === -1"
                                    title="取消删除"
                                />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="name"
                        label="设备名称"
                        min-width="200"
                        align="left"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="equipmentType"
                        label="设备类别"
                        min-width="200"
                        align="left"
                    >
                    </el-table-column>
                    <el-table-column prop="specificationModel" label="规格型号" width="150">
                    </el-table-column>
                    <el-table-column prop="unit" label="计量单位" width="120">
                    </el-table-column>
                     <el-table-column prop="textureOfMaterial" label="材质" width="120">
                      <template slot-scope="{ row }">
                            <el-input
                                v-model="row.textureOfMaterial"
                                placeholder="请输入内容"
                                v-if="isAdd && row.changeState === 1"
                               @change="input(row)"
                            ></el-input>
                            <div v-else>{{ row.textureOfMaterial }}</div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="quantity" label="数量" width="120" align="right">
                    </el-table-column>
                    <el-table-column prop="unitPrice" label="单价(元)" width="120" align="right">
                    </el-table-column>
                    <el-table-column prop="amount" label="金额(元)" width="120" align="right">
                    </el-table-column>
                    <el-table-column prop="quantityAfterChange" label="数量"  align="right"  width="120">
                        <template slot="header">
                            <div class="tab-header">数量<span class="tab-heade-icon">变</span></div>
                        </template>
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.quantityAfterChange"
                                placeholder="请输入内容"
                                v-if="isEdit && row.changeState !== -1"
                                v-enterJustFloat2
                                @change="onCalcAmount(row,'quantityUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.quantityAfterChange }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.numberRecords)"
                                @clickIcon="clickIcon(row.numberRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="unitPriceAfterChange" label="单价(元)" align="right" width="120">
                        <template slot="header">
                            <div class="tab-header">单价(元)<span class="tab-heade-icon">变</span></div>
                        </template>
                        <template slot-scope="{ row }">
                            <el-input
                                v-model="row.unitPriceAfterChange"
                                placeholder="请输入内容"
                                v-if="isEdit && row.changeState !== -1"
                                v-enterJustFloat
                                @change="onCalcAmount(row,'unitPriceUpdateFlag')"
                            ></el-input>
                            <div v-else>{{ row.unitPriceAfterChange }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.priceRecords)"
                                @clickIcon="clickIcon(row.priceRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amountAfterChange" label="金额(元)" align="right" width="120">
                        <template slot="header">
                            <div class="tab-header">金额(元)<span class="tab-heade-icon">变</span></div>
                        </template>
                        <template slot-scope="{ row }">
                            <div>{{ row.amountAfterChange }}</div>
                            <historyUpdateTable
                                v-if="checkEmpty(row.amountRecords)"
                                @clickIcon="clickIcon(row.amountRecords)"
                                :historyTable="historyTableData"
                            />
                        </template>
                    </el-table-column>
              </el-table>
            </div>
         </div>
    </div>
</template>
<script>
import { isFourInput, isNumInput, isTwoInput, isFourInputJust } from '@/utils/rules.js'
import { mapState, mapMutations, mapActions } from 'vuex'
import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/balanceContract/materialContract/ctMaterialPurchase/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
import service from '@/utils/request'
const {  httpPost } = service
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        formData: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        subcontract: { //接口
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            serverList: state => state.contract.ctClassify.serverList, //服务清单数据
            supplyType: state => state.contract.ctClassify.supplyTypeList,
            menuid: state => state.contract.ctClassify.menuid, //当前菜单的menuid
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        },
        pickerOptions () {
            return row=>{
                return {
                    disabledDate: time => {
                        if (time.getTime() < new Date(row.mobilizationTime).getTime() - 24 * 60 * 60 * 1000) {
                            return true
                        }
                    },
                }
            }
        },
    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: false,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            addFlag: true,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
            tableSelect: [],
            equipmentStatusList: ['良好', '一般', '差'], //设备现状
            planList: [
                { value: 1, label: '维保申请' },
                { value: 2, label: '大修计划' },
                { value: 3, label: '设备台账' },
            ], //1 :'维保申请', 2:'大修计划', 3:'设备台账'
            materialUseList: []//物资用途
        }
    },
    created () {
        this.getData()
    },
    mounted () {
        this.setServerList([])
        this.setTimeUnitList()
        //获取一级物资类别
        httpPost({
            url: '/material/categoryLibrary/queryListByParentClassId',
            params: {
                'parentiId': '0',
            }
        }).then(res=>{
            this.materialUseList =  res.map(x=>{
                const obj = {
                    label: x.className,
                    value: x.billId
                }
                return obj
            })
        })
    },
    methods: {
        ...mapMutations(
            'contract', ['setServerList']
        ),
        ...mapMutations(['setHistoryTableData', 'setSelectedInfo']),
        ...mapActions(
            'equip', ['setTimeUnitList']
        ),
        // 获取列表数据
        getData () {
            this.showTable = false
            //获取设备清单
            this.subcontract.getContractList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                res.forEach(item=>{
                    item.typeId = parseInt(item.typeId)
                    item.changeType = 0
                    if(this.state === 1) {
                        item.leaseTermUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                this.tableData = res
                this.showTable = true
            })
        },
        // 输入后计划金额
        onCalcAmount (row, feild) {
            this.$emit('isMonitorTaxRate')
            if(this.state === 1) {
                row.amountUpdateFlag = true
                row[feild] = true
            }
            row.amountAfterChange = (row.changeState !== -1) ?  (parseFloat(row.quantityAfterChange ? row.quantityAfterChange : 0) +  parseFloat(row.unitPriceAfterChange ? row.unitPriceAfterChange : 0)).toFixed(2) : 0
            if(row.changeState !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
                row.changeState = row.changeState === 1 ? 1 : 2
            }

        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.billId} row-hide`
            }else{
                if(row.changeState === 1) {
                    return `class-${row.billId} green row-show`
                }else if(row.changeState === 2) {
                    return `class-${row.billId} yellow row-show`
                }else if(row.changeState === -1) {
                    return `class-${row.billId} red row-show`
                }else{
                    return `class-${row.billId} row-show`
                }
            }
        },
        isFourInput (event) {
            isFourInput(event)
        },
        isFourInputJust (event) {
            isFourInputJust(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },
        deleteData () {
            if(this.tableSelect.length === 0) return
            this.clientPop('err', this.moreDeleteListErr(this.tableSelect), () => {
                this.$emit('isMonitorTaxRate')
                this.tableSelect.forEach(item=>{
                    if(item.changeType === 1 && item.changeState === 1 ) {
                        let index = this.tableData.findIndex(x=>x === item)
                        this.tableData.splice(index, 1)
                    }else if(item.changeType !== 1 && item.changeState === 1) {
                        item.changeType = -1
                        item.changeState = -1
                    }
                    else{
                        item.changeType = -2
                        item.changeState = -1
                    }
                })
            })
        },
        deleteEle (row) {
            this.clientPop('err', this.oneDeleteListErr, () => {
                this.$emit('isMonitorTaxRate')
                if(row.changeType === 1 && row.changeState === 1 ) {
                    let index = this.tableData.findIndex(x=>x === row)
                    this.tableData.splice(index, 1)
                }else if(row.changeType !== 1 && row.changeState === 1) {
                    row.changeType = -1
                    row.changeState = -1
                }
                else{
                    row.changeType = -2
                    row.changeState = -1
                }
            })
        },
        changeSelect (selection) {
            this.tableSelect = selection
        },
        //取消删除
        cancelDelete (row) {
            row.changeState = 2
            row.changeType = 2
        },
        //计时单位切换
        selectTimingUnit (row) {
            if( !row.timingUnitId )return
            row.timingUnit = this.timeUnitList.find(x => x.value === row.timingUnitId).label
            this.input(row)
        },
        changeTypeId (row) {
            if( !row.typeId )return
            row.typeName = this.serverType.find(x => x.value === row.typeId).label
            this.input(row)
        },
        //改变changeType
        input (row) {
            if(row.changeState !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
                row.changeState = row.changeState === 1 ? 1 : 2
            }
        },
        //选择物资基础库
        selectBasics () {
            selectDataClient({
                SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    'categoryId': '00000',
                    'isUpdate': false,
                    'keyword': ''
                }),
                Title: '选择设备基础库' // 标题

            }).then(val => {
                val.forEach(item=>{
                    const obj =    {
                        'amount': 0,
                        'amountAfterChange': 0,
                        'amountUpdateFlag': true,
                        'billId': '',
                        'changeState': 0,
                        'changeType': 1,
                        'equipmentType': item.categoryName,
                        'equipmentTypeId': item.categoryId,
                        'name': item.equipmentName,
                        'quantity': 0,
                        'quantityAfterChange': 0,
                        'quantityUpdateFlag': true,
                        'sourceId': this.billid,
                        'specificationModel': item.specificationModel,
                        'unit': item.unit,
                        'unitPrice': 0,
                        'unitPriceAfterChange': 0,
                        'unitPriceUpdateFlag': true,
                    }
                    this.onCalcAmount(obj)
                    this.tableData.push(obj)

                })
            })
        },
        //选择物资库存
        selectStock () {
            selectDataClient({
                SelectServiceToken: '/material/stock/listProjectDepartmentStockForSaleContract', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '',
                Title: '选择物资' // 标题
            }).then(val => {
                val.forEach(item=>{
                    let findObj = this.tableData.find(x=>x.typeId === item.materialClassId && x.unit === item.unit && x.specificationModel === item.spec && x.materialNameId === item.materialId && x.changeType !== -1)
                    if(!findObj) {
                        const obj =    {
                            'amount': 0,
                            'amountAfterChange': 0,
                            'amountUpdateFlag': true,
                            'billId': '',
                            'changeState': 1,
                            'changeType': 1,
                            'oriUnitPrice': null,
                            'quantity': item.quantity,
                            'sourceId': this.billid,
                            'specificationModel': item.spec,
                            'unit': item.unit,
                            'unitPrice': '',
                            'unitPriceAfterChange': 0,
                            'unitPriceUpdateFlag': true,
                            'oriBillId': item.billId,
                            'oriQuantity': item.quantity,
                            'materialName': item.materialName,
                            'materialNameId': item.materialId,
                            'materialUse': '',
                            'materialUseId': '',
                            'oneLevelTypeId': '',
                            'oneLevelTypeName': '',
                            'quantityAfterChange': 0,
                            'quantityUpdateFlag': true,
                            'textureOfMaterial': '',
                            'typeId': item.materialClassId,
                            'typeName': item.materialClassName,
                        }
                        this.onCalcAmount(obj)
                        this.tableData.push(obj)
                    }else{
                        findObj.quantity = findObj.quantity + item.quantity
                        this.onCalcAmount(findObj)
                    }
                })
            })
        },
        //切换物资用途
        selectMaterialUse (row) {
            if( !row.materialUseId )return
            row.materialUse = this.materialUseList.find(x => x.value === row.materialUseId).label
            this.input(row)
        }
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(2){
            .cell{
                justify-content: center;
            }
        }
        td:nth-child(6),td:nth-child(7),td:nth-child(8){
            .cell{
                justify-content: flex-end;
            }
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
</style>
